﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tycho.Runtime;

namespace Tycho.Persistence {
    public class IdentityMap {
        Dictionary<Guid, AnyObject> _objects;
        Dictionary<AnyObject, Guid> _references;

        public IdentityMap () {
            _objects = new Dictionary<Guid, AnyObject> ();
            _references = new Dictionary<AnyObject, Guid> ();
        }

        public AnyObject FindObject (Guid id) {
            AnyObject obj;

            if (_objects.TryGetValue (id, out obj)) {
                return obj;
            } else {
                return null;
            }
        }

        public Guid GetReference (AnyObject obj) {
            Guid id;

            if (_references.TryGetValue (obj, out id)) {
                return id;
            } else {
                id = Guid.NewGuid ();
                _references.Add (obj, id);
                return id;
            }
        }

        public IEnumerable<AnyObject> Objects {
            get {
                return _references.Keys;
            }
        }

        public IEnumerable<Guid> References {
            get {
                return _objects.Keys;
            }
        }
    }
}
